package tree;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 530. 二叉搜索树的最小绝对差
 * User: Li_yizYa
 * Date: 2025/6/8
 * Time: 22:22
 */
public class Solution29 {
    public int getMinimumDifference1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        int min = Integer.MAX_VALUE;
        TreeNode cur = root;
        TreeNode pre = null;
        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (pre != null) {
                    min = Math.min(cur.val - pre.val, min);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return min;
    }
    /**
     * 递归
     */
    TreeNode pre;
    int min = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) {
            return 0;
        }
        traversal(root);
        return min;
    }
    private void traversal(TreeNode root) {
        if (root == null) {
            return;
        }
        traversal(root.left);
        if (pre != null) {
            min = Math.min(root.val - pre.val, min);
        }
        pre = root;
        traversal(root.right);
    }
}
